package activity

import (
	"fmt"
	"gq_volunteer_platform/bean"
	"gq_volunteer_platform/model/activity"
	"gq_volunteer_platform/model/user"
	"gq_volunteer_platform/service/message_queue"

	ServiceAdmin "gq_volunteer_platform/service/admin"

	"github.com/gin-gonic/gin"
	"github.com/lluck42/tools"
	"gorm.io/gorm"
)

func MyUserList(c *gin.Context) {

	var req struct {
		ActivityId uint `binding:"max=10000000"`
	}

	if err := c.ShouldBindQuery(&req); err != nil {
		bean.Log.Warning(err)
		c.String(400, err.Error())
		return
	}

	var one activity.Activity
	if err := bean.MysqlDb.Where("`id`=?", req.ActivityId).First(&one).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, fmt.Sprintf("数据库错误id:%d", req.ActivityId))
		return
	}

	var organization_my_ids, err = ServiceAdmin.MyOrganizationIds(c, 0)
	if err != nil {
		bean.Log.Warning(err.Error())
		c.String(400, err.Error())
		return
	}

	if !tools.InList(organization_my_ids, one.OrganizationId) {
		var err = fmt.Sprintf("没有该组织权限id:%d", one.OrganizationId)
		bean.Log.Error(err)
		c.String(403, err)
		return
	}

	// userList
	var userList []struct {
		ID           uint
		UserId       uint
		Name         string
		MobileNumber string
		ProfilePhoto string

		CreatedAt       string
		CheckStatus     string
		SignStatus      string
		ExitCheckStatus string
		Point           uint
	}

	if err := bean.MysqlDb.Model(&activity.ActivityUser{}).
		Select("`activity_user`.`id`,`user`.`id` as user_id,`user`.`real_name` as name,`user`.`mobile_number`,`user`.`profile_photo`,`activity_user`.`created_at`,`activity_user`.`check_status`,`activity_user`.`sign_status`,`activity_user`.`exit_check_status`,? as point", one.ServeHour).
		Joins("LEFT JOIN `user` on `user`.`id` = `activity_user`.`user_id`").
		Where("`activity_user`.`activity_id`=?", one.ID).Find(&userList).Error; err != nil {

		bean.Log.Warning(err)
		c.String(400, fmt.Sprintf("活动不存在id:%d", one.ID))
		return
	}

	c.PureJSON(200, userList)
}

func MyUserExitCheckList(c *gin.Context) {

	var req struct {
		Page           int    `binding:"required,gte=1"`
		Limit          int    `binding:"required,gte=1"`
		Name           string `binding:"max=255"`
		OrganizationId uint   `binding:"max=10000000"`
	}

	if err := c.ShouldBindQuery(&req); err != nil {
		bean.Log.Warning(err.Error())
		c.String(400, err.Error())
		return
	}

	var offset = (req.Page - 1) * req.Limit

	var organization_my_ids, err = ServiceAdmin.MyOrganizationIds(c, req.OrganizationId)
	if err != nil {
		bean.Log.Warning(err.Error())
		c.String(400, err.Error())
		return
	}

	// 查询
	var count int64

	var tx = bean.MysqlDb.Model(&activity.ActivityUser{})

	tx = tx.Where("`activity_user`.`organization_id` in ?", organization_my_ids)
	tx = tx.Where("`activity_user`.`exit_check_status`=?", "待审核")

	if req.Name != "" {
		tx = tx.Where("`name` like ?", "%"+req.Name+"%")
	}

	// 查询总数
	if err := tx.Count(&count).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	// userList
	var userList []struct {
		ID             uint
		OrganizationId uint
		ActivityName   string

		Name         string
		MobileNumber string
		ProfilePhoto string

		CreatedAt       string
		CheckStatus     string
		SignStatus      string
		ExitCheckStatus string
	}

	if err := tx.
		Select("`activity_user`.`id`,`activity_user`.`organization_id`,`user`.`real_name` as name,`user`.`mobile_number`,`user`.`profile_photo`,`activity_user`.`created_at`,`activity_user`.`check_status`,`activity_user`.`sign_status`,`activity_user`.`exit_check_status`,`activity`.`name` as activity_name").
		Joins("LEFT JOIN `user` on `user`.`id` = `activity_user`.`user_id`").
		Joins("LEFT JOIN `activity` on `activity`.`id` = `activity_user`.`activity_id`").
		Limit(req.Limit).Offset(offset).
		Order("`id` DESC").
		Find(&userList).Error; err != nil {

		bean.Log.Warning(err)
		c.String(400, err.Error())
		return
	}

	c.PureJSON(200, gin.H{
		"count": count,
		"list":  userList,
	})
}

func MyUserExitCheck(c *gin.Context) {
	var req struct {
		ID uint `binding:"max=10000000"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		bean.Log.Warning(err.Error())
		c.String(400, err.Error())
		return
	}

	var one activity.ActivityUser
	if err := bean.MysqlDb.Where("`id`=?", req.ID).First(&one).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	var ExitUserId = one.UserId
	var tx = bean.MysqlDb.Begin()

	if err := tx.Delete(&one).Error; err != nil {
		tx.Rollback()
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	var two activity.Activity
	if err := bean.MysqlDb.Where("`id`=?", one.ActivityId).First(&two).Error; err != nil {
		tx.Rollback()
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	if err := tx.Model(&two).Update("`participant_count`", gorm.Expr("`participant_count` - 1")).Error; err != nil {
		tx.Rollback()
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	// 提交执行
	if err := tx.Commit().Error; err != nil {
		tx.Rollback()
		bean.Log.Error(err)
		c.String(500, "数据库错误")
		return
	}

	c.String(200, "ok")

	// 发送通知 jldtx
	// // 查询要退出的账号信息
	var user1 user.User
	if err := bean.MysqlDb.Where("`id`=?", ExitUserId).First(&user1).Error; err != nil {
		bean.Log.Error(err)
		return
	}

	var Openid = user1.Openid
	var page = "pages/index/index"
	var applyProject = two.Name
	var applyTime = two.UpdatedAt
	var applyResult = "您已退出活动"

	if err := message_queue.MessageQueueAddT1(Openid, page, applyProject, applyTime, applyResult); err != nil {
		// 错误记录
		bean.Log.Error(err)
		return
	}

}

func MyUserCheck(c *gin.Context) {
	var req struct {
		ID          uint   `binding:"max=10000000"`
		CheckStatus string `binding:"oneof=已驳回 已审核"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		bean.Log.Warning(err.Error())
		c.String(400, err.Error())
		return
	}

	var organization_my_ids, err = ServiceAdmin.MyOrganizationIds(c, 0)
	if err != nil {
		bean.Log.Warning(err.Error())
		c.String(400, err.Error())
		return
	}

	var one activity.ActivityUser
	if err := bean.MysqlDb.Where("`id`=?", req.ID).First(&one).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	if !tools.InList(organization_my_ids, one.OrganizationId) {
		var err = fmt.Sprintf("没有该组织权限id:%d", one.OrganizationId)
		bean.Log.Error(err)
		c.String(403, err)
		return
	}

	// 状态不变动
	if one.CheckStatus == req.CheckStatus {
		c.PureJSON(200, one)
		return
	}

	var tx = bean.MysqlDb.Begin()

	if req.CheckStatus == "已审核" {
		if err := tx.Model(&activity.Activity{}).Where("`id`=?", one.ActivityId).Update("`participant_count`", gorm.Expr("`participant_count` + 1")).Error; err != nil {
			tx.Rollback()
			bean.Log.Error(err)
			c.String(500, err.Error())
			return
		}
	} else if req.CheckStatus == "已驳回" {
		if err := tx.Model(&activity.Activity{}).Where("`id`=?", one.ActivityId).Update("`participant_count`", gorm.Expr("`participant_count` - 1")).Error; err != nil {
			tx.Rollback()
			bean.Log.Error(err)
			c.String(500, err.Error())
			return
		}
	}

	var two activity.ActivityUser
	two.ID = one.ID
	two.CheckStatus = req.CheckStatus

	if err := tx.Updates(&two).Error; err != nil {
		tx.Rollback()
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	// 提交执行
	if err := tx.Commit().Error; err != nil {
		tx.Rollback()
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	c.PureJSON(200, one)

	// 发送通知 jldtx
	var activity_list activity.Activity
	if err := bean.MysqlDb.Where("id=?", one.ActivityId).First(&activity_list).Error; err != nil {
		bean.Log.Warning(err)
		c.String(400, fmt.Sprintf("活动不存在id:%d", req.ID))
		return
	}

	var user_list struct {
		ID        uint
		Openid    string
		CreatedAt string
	}
	if err := bean.MysqlDb.Unscoped().Model(&user.User{}).Where("`id`=?", one.UserId).First(&user_list).Error; err != nil {
		bean.Log.Error(err)
		return
	}

	var Openid = user_list.Openid
	var page = "pages/index/index"
	var applyProject = activity_list.Name + "报名申请"
	var applyTime = one.UpdatedAt
	var applyResult = ""
	if req.CheckStatus == "已驳回" {
		applyResult = "您的申请已驳回"
		if err := message_queue.MessageQueueAddT1(Openid, page, applyProject, applyTime, applyResult); err != nil {
			// 错误记录
			bean.Log.Error(err)
		}
	}

}
